package com.weirdor.wchat.admin.web;

import com.weirdor.wchat.common.utils.R;
import com.weirdor.wchat.module.entity.SysUser;
import com.weirdor.wchat.module.service.ISysTokenService;
import com.weirdor.wchat.module.service.ISysUserService;
import com.weirdor.wchat.module.utils.ShiroUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录相关
 *
 * @author weirdor
 */
@RestController
@RequestMapping("/admin")
public class SysLoginController{

	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysTokenService sysUserTokenService;
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public R login(String username, String password) {
		SysUser user = sysUserService.queryByUserName(username);
		//账号不存在、密码错误
		if (user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if (user.getStatus() == 0) {
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}
	
}
